/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package banksystem;
import java.awt.Color;
import java.awt.event.ItemEvent;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.JComboBox;
/**
 *
 * @author ROBM
 */
public class CreateAccountFrame extends javax.swing.JFrame {

	Controller mController;
	HashMap<Long, Account> mAccountMap;
	/**
	 * Creates new form CreateAccountFrame
	 */
	public CreateAccountFrame(Controller controller, HashMap<Long, Account> accounts) {
		this.mController = controller;
		this.mAccountMap = accounts;
		initComponents();
		
		this.typeLabel.setText("Account Type: " + jComboBox1.getSelectedItem().toString());
		try{
			this.interestLabel.setText("Interest Rate: " + ((AccountType)jComboBox1.getSelectedItem()).getInterestRate());
			this.minimumLabel.setText("Minimum Balance: " + ((AccountType)jComboBox1.getSelectedItem()).getMinimumBalance());
		}catch(ClassCastException e){
			throw e;
		}

		this.errorLabel.setVisible(false);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        selectTypeLabel = new javax.swing.JLabel();
        setBalanceLabel = new javax.swing.JLabel();
        balanceFeild = new javax.swing.JTextField();
        submitButton = new javax.swing.JButton();
        jComboBox1 = new JComboBox<AccountType>(AccountType.values());
        typeLabel = new javax.swing.JLabel();
        minimumLabel = new javax.swing.JLabel();
        interestLabel = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        errorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        selectTypeLabel.setText("Selcet Account Type");

        setBalanceLabel.setText("Account Balance:");

        submitButton.setText("Submit");
        submitButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                submitButtonMouseClicked(evt);
            }
        });

        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        typeLabel.setText("Account Type: ");

        minimumLabel.setText("Minimum Balance: ");

        interestLabel.setText("Interest Rate: ");

        cancelButton.setText("Cancel");
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelButtonMouseClicked(evt);
            }
        });

        errorLabel.setForeground(new java.awt.Color(204, 0, 0));
        errorLabel.setText("Error");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(submitButton)
                            .addComponent(setBalanceLabel)
                            .addComponent(balanceFeild, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(selectTypeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(69, 69, 69)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(typeLabel)
                                    .addComponent(minimumLabel)
                                    .addComponent(interestLabel))
                                .addGap(0, 82, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cancelButton))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(errorLabel)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(selectTypeLabel)
                    .addComponent(typeLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(interestLabel))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(setBalanceLabel)
                    .addComponent(minimumLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(balanceFeild, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(errorLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 129, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(submitButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void submitButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_submitButtonMouseClicked
		AccountType type; 
		double amount;
		
		try{
			type = (AccountType) this.jComboBox1.getSelectedItem();
		}catch(ClassCastException e)
		{
			this.errorLabel.setText("Error: " + e.getLocalizedMessage());
			this.errorLabel.setVisible(true);
			return;
		}
		try{
			amount = this.currencyToDouble(this.balanceFeild.getText());
		}catch(NumberFormatException e){
			this.errorLabel.setText("Error: Please Enter A Valid Amount");
			this.errorLabel.setVisible(true);
			return;
		}
		try{
			if(amount >= type.getMinimumBalance())
			{
				this.mController.CreateAccount(createName(type), type, amount);
			}else{
				this.minimumLabel.setForeground(Color.red);
			}
		}catch(NullPointerException e){
			this.errorLabel.setText("Error: " + e.getLocalizedMessage());
			this.errorLabel.setVisible(true);
			throw(e);
		}
	}//GEN-LAST:event_submitButtonMouseClicked

	private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
		JComboBox<AccountType> temp; 
		AccountType type;
		
		try{
			temp = (JComboBox<AccountType>)evt.getSource();
			type = (AccountType) temp.getSelectedItem();
		}catch(ClassCastException e)
		{
			this.errorLabel.setText("Error: " + e.getLocalizedMessage());
			this.errorLabel.setVisible(true);
			return;
		}
		if(evt.getStateChange() == ItemEvent.SELECTED)
		{ 
			this.typeLabel.setText("Account Type: " + type.toString());
			this.typeLabel.setVisible(true);
			this.interestLabel.setText("Interest Rate: " + type.getInterestRate());
			this.interestLabel.setVisible(true);
			this.minimumLabel.setText("Minimum Balance: " + type.getMinimumBalance());
			this.minimumLabel.setVisible(true);
		}
	}//GEN-LAST:event_jComboBox1ItemStateChanged

	private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseClicked
		this.mController.SaveAndRestart(this);
	}//GEN-LAST:event_cancelButtonMouseClicked

	private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jComboBox1ActionPerformed

	protected double currencyToDouble(String str) 
			throws NumberFormatException, NullPointerException
	{
		double num;
		
		if(str.matches("\\$?[0-9]*\\.?[0-9]{0,2}"))
		{
			str = str.replaceFirst("[$]", "");
			num = Double.valueOf(str);
		}else{
			throw new NumberFormatException("Invalid Currency");
		}
		
		return num;
	}
	
	
	protected String createName(AccountType type)
	{
		int j = 1;
		boolean match;
		String tmp = null;
		Account account;
		
		for(Iterator<Account> i = this.mAccountMap.values().iterator(); i.hasNext(); )
		{
			
			account = i.next();
			if(account.getType() != null)
			{	
				if(account.getType() == type)
				{
					tmp = account.getName();
				}
			}
		}
		
		if(tmp != null)
		{
			j = Integer.valueOf(tmp.replaceAll("[a-zA-Z]* ", ""));
			j++;
		}
		
		return type.toString() + " " + j;
	}
	

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField balanceFeild;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel errorLabel;
    private javax.swing.JLabel interestLabel;
    private javax.swing.JComboBox<AccountType> jComboBox1;
    private javax.swing.JLabel minimumLabel;
    private javax.swing.JLabel selectTypeLabel;
    private javax.swing.JLabel setBalanceLabel;
    private javax.swing.JButton submitButton;
    private javax.swing.JLabel typeLabel;
    // End of variables declaration//GEN-END:variables
}
